<?php

class CategoryController extends BackendController
{

    /**
     * 分类详情
     * @param $id
     * @throws CHttpException
     */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

    /**
     * 新增分类
     */
	public function actionCreate()
	{
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];

            $file = CUploadedFile::getInstance($model, 'thumb'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $model->thumb = XUpload::createFile($file,'');
            }

			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Create Success'));
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

    /**
     * 更新分类
     * @param $id
     * @throws CHttpException
     */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $thumb = $model->thumb; //取出数据库中缩微图

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];

            $file = CUploadedFile::getInstance($model, 'thumb'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $model->thumb = XUpload::createFile($file, $thumb);
            }else{
                $model->thumb = $thumb;
            }

            // 更新图片时，没有上传新图片，thumb验证后保存会被清空，只有将验证改为：'on'=>'insert'才能正常，所以更新时没有验证图片的格式和大小
			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Update Success'));
				$this->redirect(array('index','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

    /**
     * 删除分类
     * @param $id
     * @throws CDbException
     * @throws CHttpException
     */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

    /**
     * 批量删除内容
     * throws CHttpException
     */
    public function actionDeleteAll()
    {
        $request = Yii::app()->request;
        if (!$request->isAjaxRequest || !$request->isPostRequest)
            return;

        $ids = $_POST['selection'];
        $criteria = new CDbCriteria;
        $criteria->addInCondition('id', $ids);
        if (Category::model()->deleteAll($criteria))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
        echo CJSON::encode(['result' => true]);
    }

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria = new CDbCriteria();
        $criteria->order = 'sort ASC,parent_id ASC';
        $criteria->condition = '';
        $count = Category::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 1000;
        $pages->applyLimit($criteria);
        $list = Category::model()->findAll($criteria);
        $datalist = Category::getCategoryTree(0, $list);
        $this->render('index', array('count'=>$count,'list' => $datalist, 'pages' => $pages));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Category('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Category']))
			$model->attributes=$_GET['Category'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Category the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Category::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Category $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
